import asyncio
import time


# task函数改为async 表示异步
async def task(number):
    print(f"task {number} start at: {time.time()}")
    print(number)
    # 用asyncio.sleep代替time.sleep,前者是异步sleep
    await asyncio.sleep(number)
    print(f"task {number} end at: {time.time()}")


async def main():
    work_queue = [4, 3, 2, 1]
    tasks = []
    for work in work_queue:
        # 使用asyncio.create_task将task装换成协程对象
        tasks.append(asyncio.create_task(task(number=work)))
    # 用asyncio.gather同时await任务列表
    await asyncio.gather(*tasks)


if __name__ == "__main__":
    # 用asyncio.run来执行主程序
    asyncio.run(main())
